/**
 * send email
 */

const nodemailer = require('nodemailer')
const smtpTransport = require('nodemailer-smtp-transport')
const config = require('../config')
let clientIsValid = false

const transporter = nodemailer.createTransport(smtpTransport({
	host: 'smtp.qq.com',
	secureConnection: true,
	port: 465,
	auth: {
		user: config.EMAIL.account,
		pass: config.EMAIL.password
	}
}))

const verifyClient = () => {
	transporter.verify((error, success) => {
		if (error) {
			clientIsValid = false
			console.warn('邮件客户端初始化连接失败，将在一小时后重试')
			setTimeout(verifyClient, 1000 * 60 * 60)
		} else {
			clientIsValid = true
			console.log('邮件客户端初始化连接成功，随时可发送邮件')
		}
	})
}

const mailOptions = {
	from: '1161735171@qq.com', // sender address
	to: 'slm_1990@126.com', // list of receivers
	subject: 'Hello ✔', // Subject line
	text: 'Hello world ✔', // plaintext body
	html: '<b>Hello world ✔</b>' // html body
}

const sendMail = options => {
	transporter.sendMail(options || mailOptions, (error, info) => {
		if (error) {
			console.log(error);
		} else {
			console.log('Message sent: ' + info.response)
		}
	})
}

module.exports = {
	sendMail,
	verifyClient
}